// 导入Promise
import {
	request
} from '../../request/index.js'

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		FatherTabs: [{
				id: 0,
				value: '综合',
				isActive: true
			},
			{
				id: 1,
				value: '销量',
				isActive: false
			},
			{
				id: 2,
				value: '价格',
				isActive: false
			},
		],
		//列表数据
		goods_list: [],
		// 页码
		pagenum: 1,
		// total
		total: 0
	},
	//接口要的参数
	QueryPamams: {
		query: "",
		cid: "",
		pagenum: 1,
		pagesize: 10
	},
	
	//总页数
	totalPages : 1,

	onLoad: function(options) {
		this.QueryPamams.cid = options.cid || "";
		this.QueryPamams.query = options.query || "";
		this.getGoodList()
	},


	//请求
	async getGoodList() {
		const res = await request({
			url: "/goods/search",
			data: this.QueryPamams
		})
		// console.log(res);

		const total = res.data.message.total
		//计算一页有几条数据
		this.totalPages = Math.ceil( total / this.QueryPamams.pagesize )
		
		// 拼接数组  用data 和 请求的数据 进行数组拼接
		this.setData({
			goods_list: [...this.data.goods_list,...res.data.message.goods]
		})
		// console.log(goods_list);
		//关闭刷新窗口
		wx.stopPullDownRefresh()

	},

	handleTabsItemChange(e) {
		// console.log(e);
		// 赋值
		const index1 = e.detail
		// console.log(index);
		// 修改原数组
		let {
			FatherTabs
		} = this.data
		FatherTabs.forEach((item, index2) => {
			index2 === index1 ?
				item.isActive = true :
				item.isActive = false;
		})
		// 赋值
		this.setData({
			FatherTabs
		})
	},

	//滚动条触底事件
	onReachBottom() {
		//判断是否又下一页数据
		if(this.QueryPamams.pagenum >= this.totalPages){
			wx.showToast({ title:"数据加载完毕"})
		}else{
			this.QueryPamams.pagenum += 1
			this.getGoodList()  
		}
	},
	
	//下拉刷新
	onPullDownRefresh(){
		this.setData({
			goods_list: []
		})
		this.QueryPamams.pagenum = 1
		this.getGoodList()
	}

})
